/*  Copyright 2008 Rene Weiskircher 
    This file is part of SUPA.

    SUPA is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    SUPA is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with SUPA.  If not, see <http://www.gnu.org/licenses/>.
 */
/**
 * @author Rene Weiskircher (rene.weiskircher@gmail.com) 
 */
package supa;

import java.io.PrintStream;
import java.util.Queue;

import supa.PovrayProcessor.ProcessEvent;

/**
 * @author rene
 *
 */
public class ShellOutput extends Thread {

	/**
	 * the queue that the events will be read from
	 */	
	private Queue<ProcessEvent> _eventQueue;
	/**
	 * the messages will be printed to here
	 */
	private PrintStream _out;
	/**
	 * true if the threat should retire
	 */
	private boolean _retire;

	/**
	 * Initializes the priority of the thread to minimal
	 * @param q the queue where the events will be stored
	 * @param out the stream where messages will be printed to
	 */
	public ShellOutput(Queue<ProcessEvent> q, PrintStream out) {
		this._eventQueue = q;
		this.setPriority(MIN_PRIORITY);
		this._out = out;
		this._retire = false;
	}
	

	/** prints the events from time to time from the queue
	 * @see java.lang.Thread#run()
	 */
	@Override
	public void run() {
		while(true) {
			try {
				Thread.sleep(1000);
			} catch (InterruptedException e) {
				e.printStackTrace();
				System.exit(1);
			}
			while(!_eventQueue.isEmpty()) {
				PovrayProcessor.ProcessEvent p = null;
				synchronized (_eventQueue) {
					p = _eventQueue.remove();					
				}
				for(int i = 0; i < p.processor; i++) {
					_out.append('\t');
				}
				_out.println(p.frame);
			}
			_out.flush();
			if(_retire)
				break;
		}
	}

/**
 * tells the thread to stop operations as soon as the queue is empty
 */
	public void retire() {
		this._retire = true;
	}

}
